package cn.wolfcode.rbac.servicesImpl;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.service.PermissionService;
import cn.wolfcode.rbac.util.PageResult;
import cn.wolfcode.rbac.util.QueryObject;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;


@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    ApplicationContext ctx;
    @Override
    public void delete(long id) {
        permissionMapper.deleteById(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectList(null);
    }


    @Override
    public PageResult query(QueryObject qo) {
        int row = permissionMapper.selectForCount(qo);
        if(row == 0){
            return new PageResult();
        }
        List<Permission> data = permissionMapper.selectForList(qo);
        return new PageResult(qo.getCurrentPage(),qo.getPageSize(),data,row);
    }

    @Override
    public void reload() {
        //1 首先上数据库中查询出所有的表达式
        List<String> expressions = permissionMapper.selectAllExpression();
        //2获取所有的controller
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> values = beansWithAnnotation.values();
        for (Object value : values) {
            //获取所有controller中的方法
            Method[] methods = value.getClass().getMethods();
            for (Method method : methods) {
                //判断方法上是否有该注解并且判断数据库中是否有这个表达式了
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                if(annotation!=null && !expressions.contains(annotation.value()[1])){
                    Permission p = new Permission();
                    p.setName(annotation.value()[0]);
                    p.setExpression(annotation.value()[1]);
                    permissionMapper.insert(p);
                }
            }
        }
    }
}
